package com.guigu.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.ResultCode;
import com.guigu.eduservice.entity.Businessman;

import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.service.BusinessmanEquipmentService;
import com.guigu.eduservice.service.BusinessmanService;
import com.guigu.eduservice.service.EquipmentService;
import com.guigu.eduservice.utils.MD5;
import com.guigu.eduservice.vo.BusinessmanVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.guigu.common.utils.R;
import com.guigu.eduservice.dto.UserDto;

import com.guigu.eduservice.utils.EmployeeJwtUtils;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 业务员表（含检测评估师，负责设备检测、求购跟进） 前端控制器
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/eduservice/businessman")
public class BusinessmanController {
    @Autowired
    private BusinessmanService businessmanService;

    @Autowired
    private BusinessmanEquipmentService businessmanEquipmentService;

    @Autowired
    private EquipmentService equipmentService;
    //员工登录
    @PostMapping("login")
    public R Login(@RequestBody UserDto userDto) {
        String login = businessmanService.EmployeeLogin(userDto);
        System.out.println("token:"+ login);
        if (Objects.equals(login, "用户不存在")){
            
            return R.error().message("用户不存在").code(ResultCode.USER_NOT_EXIST);
        }
        if (Objects.equals(login, "密码错误")){

            return R.error().message("密码错误").code(ResultCode.USER_PASSWORD_ERROR);
        }
        if (Objects.equals(login, "用户被禁用")){
            return R.error().message("用户被禁用").code(ResultCode.USER_DISABLE);
        }
        return R.ok().data("token", login);
    }
    //登录信息(包括名字和用户类型的)
    @PostMapping("/loginInfo")
    public R loginInfo(HttpServletRequest request) {
        // 解析请求对象（从请求对象的头部取出token）
        String name = EmployeeJwtUtils.getUserNameByJwtToken(request);
        String userType = EmployeeJwtUtils.getUserTypeByJwtToken(request);
        Businessman businessman = new Businessman();
        //接受
        businessman.setName(name);
        businessman.setDepartment(userType);
        return R.ok().data("businessman", businessman);
    }

    //业务员的分页查询
    @PostMapping("/getBusinessmanPage/{pageNum}/{pageSize}")
    public PageInfo<Businessman> getBusinessmanAll(@RequestBody BusinessmanVo vo, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        return businessmanService.getBusinessmanAll(vo,pageNum,pageSize);
    }
    //业务员的所有消息
    @GetMapping("/userInfo")
    public R userInfo(HttpServletRequest request) {
        Long id = Long.valueOf(EmployeeJwtUtils.getUserIDByJwtToken(request));
        QueryWrapper<Businessman> wrapper = new QueryWrapper<>();
        wrapper.eq("businessman_id", id);
        Businessman businessman = businessmanService.getOne(wrapper);
        return R.ok().data("businessman", businessman);
    }
    //校验旧密码
    @GetMapping ("/VerifyPassword/{Password}")
    public R checkPassword(@PathVariable String Password,HttpServletRequest request) {
        int businessmanId = EmployeeJwtUtils.getUserIDByJwtToken(request);
        QueryWrapper<Businessman> wrapper = new QueryWrapper<>();
        wrapper.eq("businessman_id", businessmanId);
        Businessman businessman = businessmanService.getOne(wrapper);
        String oldPassword = businessman.getPassword();

        if(!MD5.encrypt(Password).equals(oldPassword))
            return R.error().message("旧密码错误").code(ResultCode.USER_PASSWORD_ERROR);
        return R.ok().message("旧密码正确").code(ResultCode.SUCCESS);
    }
    //修改密码
    @PostMapping("/updatePassword/{newPassword}")
    public R updatePassword(@PathVariable String newPassword,HttpServletRequest request) {
        int businessmanId = EmployeeJwtUtils.getUserIDByJwtToken(request);
        QueryWrapper<Businessman> wrapper = new QueryWrapper<>();
        wrapper.eq("businessman_id", businessmanId);
        Businessman businessman = businessmanService.getOne(wrapper);
        businessman.setPassword(MD5.encrypt(newPassword));
        boolean update = businessmanService.updateById(businessman);
        if ( update){
            return R.ok().message("修改密码成功,请重新登录").code(ResultCode.SUCCESS);
        }
        return R.error().message("修改密码失败").code(ResultCode.ERROR);
    }

    /**
     * 查询所有业务员
     * @return
     */
    @GetMapping("/getAllBusinessman")
    public R getAllBusinessman(){
        List<Businessman> list = businessmanService.list();
        return R.ok().data("list",list);
    }

    //新增业务员
    @PostMapping
    public R AddBusinessman(@RequestBody Businessman businessman){
        businessman.setPassword(MD5.encrypt(businessman.getPassword()));
        boolean save = businessmanService.save(businessman);
        if (save){
            return R.ok().data("ok","添加成功");
        }
        return R.error().data("ok","添加失败");
    }

    //删除业务员
    @DeleteMapping("/{id}")
    public R DeleteBusinessman(@PathVariable("id") Integer id){
        boolean b = businessmanService.removeById(id);
        if (b){
            return R.ok().data("ok","删除成功");
        }
        return R.error().data("ok","删除失败");
    }

    //修改业务员
    @PutMapping
    public R  UpdateBusinessman(@RequestBody Businessman businessman){
        businessman.setUpdateTime(LocalDateTime.now());
        boolean b = businessmanService.updateById(businessman);
        if (b){
            return R.ok().data("ok","修改成功");
        }
        return R.error().data("ok","修改失败");
    }

    //根据Id查询
    @GetMapping("/{id}")
    public R getBusinessmanById(@PathVariable("id") Integer id){
        Businessman byId = businessmanService.getById(id);
        return R.ok().data("businessman",byId);
    }

    //根据操作员的id查询业务员
    @GetMapping("/getOperatorId/{id}")
    public R getOperatorId(@PathVariable("id") Integer id){
        Businessman operatorId = businessmanService.getOperatorId(id);
        return R.ok().data("OperatorId",operatorId);
    }

    //根据业务员的id查询设备表和业务员关联的表，再根据关联表里的设备Id查询业务员所有归属的设备
    @PostMapping("/getBusinessmanEquipmentByBusinessmanId/{BusinessmanId}")
    public R getBusinessmanEquipmentByBusinessmanId(@PathVariable("BusinessmanId") Long BusinessmanId){
        List<Equipment> businessmanEquipmentByBusinessmanId = businessmanService.getBusinessmanEquipmentByBusinessmanId(BusinessmanId);
        return R.ok().data("list",businessmanEquipmentByBusinessmanId);
    }

    //查询销售报表
    @PostMapping("/getXiaoShou/{pageNum}/{pageSize}")
    public R  getXiaShou(@RequestBody BusinessmanVo vo,
                         @PathVariable("pageNum") Integer pageNum,
                         @PathVariable("pageSize") Integer pageSize){

        PageInfo<Businessman> businessmanAll = businessmanService.getBusinessmanAll(vo, pageNum, pageSize);

        for (Businessman list : businessmanAll.getList()) {
            Integer chengJiao=0;
            Double dingDanTotal=0.00;
            //分配数量
            Integer countByBusinessmanId = businessmanService.getCountByBusinessman_id(list.getBusinessmanId());
            list.setFenPeiTotal(countByBusinessmanId);
            //==================成交订单=========================
            List<Equipment> businessmanEquipmentByBusinessmanId = businessmanService.getBusinessmanEquipmentByBusinessmanId(list.getBusinessmanId());
            for (int i=0;i<businessmanEquipmentByBusinessmanId.size();i++){
                Equipment equipment = businessmanEquipmentByBusinessmanId.get(i);
                if (equipment.getStatus()==3){
                    chengJiao++;
                    dingDanTotal+=equipment.getPrice().doubleValue();
                }
            }
            list.setChengJiaoTotal(chengJiao);
            list.setDingDanTotal(dingDanTotal);
            if (countByBusinessmanId != null && countByBusinessmanId != 0) {
                Integer zk= (int) (chengJiao.doubleValue()/countByBusinessmanId.doubleValue()*100);
                list.setChengDan( zk);
            } else {
                list.setChengDan(0); // 当没有订单时，成交率为0
            }
        }
        return R.ok().data("list",businessmanAll);
    }
    //查询单个业务员的销售报表
    @PostMapping("/getOneXiaoShou")
    public R  getOneXiaShou(HttpServletRequest request){
        int businessmanId = EmployeeJwtUtils.getUserIDByJwtToken(request);

            Integer chengJiao=0;
            Double dingDanTotal=0.00;
            Businessman One = businessmanService.getById(businessmanId);
        //分配数量
            Integer countByBusinessmanId = businessmanService.getCountByBusinessman_id((long) businessmanId);
            One.setFenPeiTotal(countByBusinessmanId);
            //==================成交订单=========================
            List<Equipment> businessmanEquipmentByBusinessmanId = businessmanService.getBusinessmanEquipmentByBusinessmanId((long) businessmanId);
            for (int i=0;i<businessmanEquipmentByBusinessmanId.size();i++){
                Equipment equipment = businessmanEquipmentByBusinessmanId.get(i);
                if (equipment.getStatus()==3){
                    chengJiao++;
                    dingDanTotal+=equipment.getPrice().doubleValue();
                }
            }
            One.setChengJiaoTotal(chengJiao);
            One.setDingDanTotal(dingDanTotal);
            if (countByBusinessmanId != null && countByBusinessmanId != 0) {
                Integer zk= (int) (chengJiao.doubleValue()/countByBusinessmanId.doubleValue()*100);
                One.setChengDan( zk);
            } else {
                One.setChengDan(0); // 当没有订单时，成交率为0
            }
            return R.ok().data("One",One);

    }
}
